#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File Name: sycn_md2halo.py
# Author: bobo
# Created Time: 20241107
# pip3 install halo
"""
上传markdown文件到halo，需要设置环境变量HALO_TOKEN,HALO_SITE
Usage:
    sync_md2halo.py [<files>...] [-d=<path>]
    sync_md2halo.py (-h | --help)
    sync_md2halo.py (-v | --version)

Options:
    -h --help  显示帮助信息
    -v --version  显示版本信息
    <files> 要处理的文件
    -d <path> 处理目录
样例： markdown文件元数据样例
title:xx
date:2024-01-01T00:00:00
tags:
- xx
- xx
categories:
- xx
cover: xx
abbrlink: xx
published: True
"""

import os
import traceback

from docopt import docopt

from utils import Halo2Uploader as halo


def get_md_file(dir: str):
    """
    获取一个目录下所有文件列表，包括子目录
    - dir: 文件路径
    """
    files_list = []
    for root, dirs, files in os.walk(dir, topdown=False):
        for file in files:
            n, ext = os.path.splitext(file)
            if ext == ".md":
                files_list.append(os.path.join(root, file))
    return files_list


def upload_md_to_halo(path: str):
    """
    同步本地目录md文件到halo
    - path: md文件目录
    """
    if os.path.isfile(path):
        md_files = [path]
    elif os.path.isdir(path):
        md_files = get_md_file(path)
    else:
        print("文件或目录异常！")
        return 0
    for md_file in md_files:
        try:
            halo.upload_md_file(md_file)
        except Exception as e:
            print("处理文件异常：", md_file, e)
            print(traceback.format_exc())
            continue


if __name__ == "__main__":
    arguments = docopt(__doc__, version="sync_md2halo.py 1.0")
    # print(arguments)
    if md_files := arguments.get("<files>"):
        for f in md_files:
            print(f"处理文件：{f}")
            upload_md_to_halo(f)
    elif path := arguments.get("-d"):
        print(f"处理目录：{path}")
        upload_md_to_halo(path)
    else:
        print(__doc__)
        exit()
    # sync("./")
